package sxhm

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

func GetParams(token string) RequestPlanParams {
	// 定义请求参数
	params := RequestPlanParams{
		URL:        "https://ticket.sxhm.com/applet/bms/visitplan/visitPlan/get",
		Token:      token,
		ID:         "1942509526422880256",
		UserAgent:  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090a13) UnifiedPCWindowsWechat(0xf254051a) XWEB/14111 Flue",
		Referer:    "https://ticket.sxhm.com/quickticket/index.html",
		Origin:     "https://ticket.sxhm.com",
		AcceptLang: "zh-CN,zh;q=0.9",
	}
	return params
}

// 发送HTTP请求的独立函数
func SendPlanRequest(params RequestPlanParams, requestNum int) error {
	// 请求体数据
	requestData := map[string]string{
		"id": params.ID,
	}

	// 将请求体转换为JSON格式
	jsonData, err := json.Marshal(requestData)
	if err != nil {
		return fmt.Errorf("请求 #%d JSON转换错误: %w", requestNum, err)
	}

	// 创建HTTP请求
	req, err := http.NewRequest("POST", params.URL, bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("请求 #%d 创建请求错误: %w", requestNum, err)
	}

	// 设置请求头
	req.Header.Set("host", "ticket.sxhm.com")
	req.Header.Set("user-agent", params.UserAgent)
	req.Header.Set("token", params.Token)
	req.Header.Set("content-type", "application/json")
	req.Header.Set("accept", "*/*")
	req.Header.Set("origin", params.Origin)
	req.Header.Set("sec-fetch-site", "same-origin")
	req.Header.Set("sec-fetch-mode", "cors")
	req.Header.Set("sec-fetch-dest", "empty")
	req.Header.Set("referer", params.Referer)
	req.Header.Set("accept-encoding", "gzip, deflate, br")
	req.Header.Set("accept-language", params.AcceptLang)
	req.Header.Set("priority", "u=1, i")

	// 创建带超时的HTTP客户端
	client := &http.Client{
		Timeout: 10 * time.Second,
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("请求 #%d 发送请求错误: %w", requestNum, err)
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("请求 #%d 读取响应错误: %w", requestNum, err)
	}

	// 输出响应状态码
	fmt.Printf("请求 #%d 状态码: %s\n", requestNum, resp.Status)

	// 可选：仅在状态码非200时输出详细内容
	// if resp.StatusCode == http.StatusOK {
	fmt.Printf("请求 #%d 响应内容: %s\n", requestNum, string(body))
	// }

	return nil
}

func GetOrderParams(token, VisitPlanId, staggeredReservationDailyId, ticketId string) RequestOrderParams {
	// 定义请求参数
	params := RequestOrderParams{
		URL:        "https://ticket.sxhm.com/applet/bms/sale_order/orderReservation",
		Token:      token,
		UserAgent:  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090a13) UnifiedPCWindowsWechat(0xf254051a) XWEB/14111 Flue",
		Referer:    "https://ticket.sxhm.com/quickticket/index.html",
		Origin:     "https://ticket.sxhm.com",
		AcceptLang: "zh-CN,zh;q=0.9",
	}
	now := time.Now()

	// 如果需要当天零点的时间
	curTime := time.Now()
	calTime := curTime.AddDate(0, 0, 5)
	year, month, day := calTime.Date()
	midnight := time.Date(year, month, day, 0, 0, 0, 0, now.Location())
	formattedMidnight := midnight.Format("2006-01-02 15:04:05")

	params.OrderData = OrderData{
		OrderType: "OFFLINE_FAST",
		OrderDetailList: []OrderDetail{
			{
				TicketId:                    ticketId,
				Quantity:                    1,
				CurrentSalePrice:            0,
				VisitorCertificateNo:        "44080219881030081X",
				VisitorCertificateType:      "1",
				VisitorMobile:               "13802885393",
				VisitorName:                 "陈华龙",
				UseStartDate:                formattedMidnight,
				StaggeredReservationDailyId: staggeredReservationDailyId,
				VisitPlanId:                 VisitPlanId,
				IsChildren:                  "F",
			},
			{

				TicketId:                    ticketId,
				Quantity:                    1,
				CurrentSalePrice:            0,
				VisitorCertificateNo:        "440105201505140018",
				VisitorCertificateType:      "1",
				VisitorName:                 "陈泓文",
				UseStartDate:                formattedMidnight,
				StaggeredReservationDailyId: staggeredReservationDailyId,
				VisitPlanId:                 VisitPlanId,
				IsChildren:                  "F",
			},
			{

				TicketId:                    ticketId,
				Quantity:                    1,
				CurrentSalePrice:            0,
				VisitorCertificateNo:        "440802201005082519",
				VisitorCertificateType:      "1",
				VisitorName:                 "陈启滔",
				UseStartDate:                formattedMidnight,
				StaggeredReservationDailyId: staggeredReservationDailyId,
				VisitPlanId:                 VisitPlanId,
				IsChildren:                  "F",
			},
			{

				TicketId:                    ticketId,
				Quantity:                    1,
				CurrentSalePrice:            0,
				VisitorCertificateNo:        "440102195204153256",
				VisitorCertificateType:      "1",
				VisitorName:                 "陈邓",
				UseStartDate:                formattedMidnight,
				StaggeredReservationDailyId: staggeredReservationDailyId,
				VisitPlanId:                 VisitPlanId,
				IsChildren:                  "F",
			},
		},
		Remark:            "小程序下单",
		IsCreateVisitPlan: "T",
	}
	return params
}

// 发送HTTP请求的独立函数
func SendOrderRequest(params RequestOrderParams, requestNum int) error {

	// 将请求体转换为JSON格式
	jsonData, err := json.Marshal(params.OrderData)
	if err != nil {
		return fmt.Errorf("请求 #%d JSON转换错误: %w", requestNum, err)
	}

	// 创建HTTP请求
	req, err := http.NewRequest("POST", params.URL, bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("请求 #%d 创建请求错误: %w", requestNum, err)
	}

	// 设置请求头
	req.Header.Set("host", "ticket.sxhm.com")
	req.Header.Set("user-agent", params.UserAgent)
	req.Header.Set("token", params.Token)
	req.Header.Set("content-type", "application/json")
	req.Header.Set("accept", "*/*")
	req.Header.Set("origin", params.Origin)
	req.Header.Set("sec-fetch-site", "same-origin")
	req.Header.Set("sec-fetch-mode", "cors")
	req.Header.Set("sec-fetch-dest", "empty")
	req.Header.Set("referer", params.Referer)
	req.Header.Set("accept-encoding", "gzip, deflate, br")
	req.Header.Set("accept-language", params.AcceptLang)
	req.Header.Set("priority", "u=1, i")

	// 创建带超时的HTTP客户端
	client := &http.Client{
		Timeout: 10 * time.Second,
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("请求 #%d 发送请求错误: %w", requestNum, err)
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("请求 #%d 读取响应错误: %w", requestNum, err)
	}

	// 输出响应状态码
	fmt.Printf("请求 #%d 状态码: %s\n", requestNum, resp.Status)

	// 可选：仅在状态码非200时输出详细内容
	// if resp.StatusCode == http.StatusOK {
	// fmt.Printf("请求 #%d 响应内容: %s\n", requestNum, string(body))
	// }

	var res OrderResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return fmt.Errorf("序列: #%d ， 错误: %w", requestNum, err)
	}
	// 数据格式
	// fmt.Printf("请求 #%d 响应内容: %s\n", requestNum, string(body))
	fmt.Printf("请求 #%d 响应内容: code: %v , error: %v \n", requestNum, res.Code, res.Error)
	if res.Code != 0 {
		if res.Code != -1 && res.Code != 6000 {
			fmt.Printf("!!!!!!!!!!!!!!!!! code: %v , error: %s \n", res.Code, res.Error)
		}
		return fmt.Errorf("序列: #%d ，返回 code: %v", requestNum, res.Code)
	} else {
		fmt.Println("!!!!!!!!!!!!!!!!!  code = 0")
	}
	return nil
}
